# coding=utf-8

from django.db import transaction
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver

from social.account.models import User
from social.search.models import EsUser


@receiver(post_save, sender=User)
def user_post_save(sender, instance: User, updated_fields=None, **kwargs):
    try:
        if not instance.is_active or instance.is_admin:
            transaction.on_commit(lambda: EsUser.delete(instance.id))
        if updated_fields and (
                'last_active' not in updated_fields
                and 'avatar_real' not in updated_fields
                and 'avatar_auth' not in updated_fields
                and not ('lat' in updated_fields and 'lng' in updated_fields)):
            return
        transaction.on_commit(lambda: EsUser.update_user(instance))
    except Exception as e:
        print(e)


@receiver(post_delete, sender=User)
def user_post_delete(sender, instance, **kwargs):
    user = EsUser.get(id=instance.id, ignore=404)
    if user:
        user.delete()
